import { GlobalData } from '/store/state'
import { getServer } from '/store/mutations'
import { mallApi } from '/api/mall'
import { userApi } from '/api/user'

Page({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    currencyName: GlobalData.currencyName,
    mall: {} as any,
    categoryId: 0,
    categories: [] as any[],
    img: [] as any[],
    title: '',
    dsc: '',
    price: 0,
    sroce: 0,
    marketPrice: '' as any,
    canPublish: false,
    user: {} as DomoUser,
    rechargeRatio: GlobalData.currency.settings['recharge-ratio'],
    buyRules: {
      start: '',
      week: '',
      number: '',
    },
    city: [],
    cityString: '',
    addTyleshow: false,
    type: [] as any,
    /** 视频 */
    videoPath: '' as string,
    videoContext: '' as any,
    videoFullScreen: false,
    iptPrice: '',
    iptSroce: '',
    vip: {} as DomoVip,
    /** 会员商品0,兑换商品1 */
    vipProduct: 0,
    /** 会员原价 */
    vipMarketPrice: '' as any,
    /** 各会员价格 */
    extra: {} as any,
    /** 有无邮费 */
    has_freight: false,
    /** 邮费 */
    freight: '' as any,
    edit: false,
    /** 商品详情数据 */
    top_text: '',
    bottom_text: '',
    content_images: [] as any,
    /** 编辑商品的ID */
    commdityId: '',
    /** 完善信息弹框 */
    show: false,
    /** 规格列表 */
    sku: [] as Sku[],
    /** 规格 */
    name: '',
    /** 库存 */
    inventory: '',
    /** 选中分类的下标 */
    sukIndex: '',
    /** 规格差价 */
    count: '',
    /** 差价提示 */
    extraPlaceholder: '设置补价（元）',
    brand: '' as any,
    brandId: '',
  },
  async onLoad({ edit = false }) {
    this.setData({
      isFullScreen: GlobalData.isFullScreen,
    })
    if (edit) {
      wx.setNavigationBarTitle({
        title: '编辑商品',
      })
      const pages = getCurrentPages()
      const lastpage = pages[pages.length - 2]
      const commdity = lastpage.data.mall_commodities
      let brand = ''
      let brandId = ''
      if (commdity.brand_id) {
        brand = commdity.brands[0]
        brandId = commdity.brand_id
      }
      if (commdity.sku) {
        commdity.sku.map((i: any) => {
          i.extra = i.extra / 100
        })
      }

      const data = {
        canPublish: true,
        edit: true,
        vipProduct: commdity.type == 'member' ? 0 : 1,
        extraPlaceholder:
          commdity.type == 'member' ? '设置补价（元）' : `设置补${GlobalData.currencyName}`,
        title: commdity.title,
        img: commdity.photos,
        buyRules: {
          week: commdity.buy_limit_days ? commdity.buy_limit_days : '',
          number: commdity.buy_limit_qty ? commdity.buy_limit_qty : '',
          start: commdity.order_min_qty ? commdity.order_min_qty : '',
        },
        dsc: commdity.buying_read,
        brand,
        brandId,
        city: commdity.remote_areas,
        cityString: commdity.remote_areas ? commdity.remote_areas.toString() : '',
        has_freight: commdity.has_freight,
        freight: commdity.freight ? commdity.freight / 100 : '',
        type: commdity.options,
        categoryId: commdity.category_id,
        top_text: commdity.top_text ? commdity.top_text : '',
        bottom_text: commdity.bottom_text ? commdity.bottom_text : '',
        content_images: commdity.content_images ? commdity.content_images : [],
        commdityId: commdity.id,
        sku: commdity.sku,
      }
      this.setData(
        commdity.type == 'member'
          ? {
              ...data,
              vipMarketPrice: commdity.market_price / 100,
              extra: { low: commdity.extra.low / 100, middle: commdity.extra.middle / 100 },
            }
          : {
              ...data,
              marketPrice: commdity.market_price / 100,
              price: commdity.price > 0 ? commdity.price / 100 : 0,
              sroce: commdity.score,
              iptPrice: `${commdity.price > 0 ? commdity.price / 100 : 0}`,
              iptSroce: `${commdity.score}`,
            },
      )
    }
  },
  async onShow() {
    const info = await mallApi.checkShoperInfo()
    if (!info.status) {
      return this.setData({
        show: true,
      })
    } else {
      this.setData({
        show: false,
      })
    }
    this.getPosition()
    this.getInfo()
    this.getVipInfo()
  },
  getPosition() {
    this.setData({
      access: GlobalData.access,
      navigationHeight: GlobalData.navigationHeight,
      mall: GlobalData.mall,
      currencyName: GlobalData.currencyName,
      rechargeRatio: +GlobalData.currency.settings['recharge-ratio'],
    })
  },
  /** 会员卡配置信息 */
  async getVipInfo() {
    const vipData = await userApi.getVipConfig()
    /** 处理VIP数据,取成自己想要的格式 */
    const vip = {} as DomoVip
    vip.switch = vipData.switch
    vip.config = []
    vipData.config.low && vipData.config.low.enable ? vip.config.push(vipData.config.low) : ''
    vipData.config.middle && vipData.config.middle.enable
      ? vip.config.push(vipData.config.middle)
      : ''
    vipData.config.high && vipData.config.high.enable ? vip.config.push(vipData.config.high) : ''
    vip.config = vip.config.filter((item: DomoVipItem) => {
      return (item.setting = item.setting.filter((items) => {
        return items.enable
      }))
    })
    this.setData({
      vip,
    })
  },
  /** 输入原价 */
  inputMarketPrice(e: WechatMiniprogram.Input) {
    this.setData(
      this.data.vipProduct == 1
        ? {
            marketPrice: e.detail.value,
          }
        : {
            vipMarketPrice: e.detail.value,
          },
    )
    this.canPublish()
  },
  /** 输入各个会员价格 */
  inputVipPrice(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { index },
      },
      detail: { value },
    } = e
    const {
      data: { extra, vip },
    } = this
    value == '' && extra[`${vip.config[index].level}`]
      ? delete extra[`${vip.config[index].level}`]
      : (extra[`${vip.config[index].level}`] = value)
    this.setData({
      extra,
    })
    this.canPublish()
  },
  async getInfo() {
    const categories = await mallApi.getCategories()
    const user = wx.getStorageSync(`${getServer()}/logged`).data
    this.setData({
      categories,
      user,
    })
  },
  /** 选择品牌 */
  chooseBrand() {
    wx.navigateTo({
      url: '/mall/publish/chooseBrands/chooseBrands',
    })
  },
  /** 选择分类 */
  chooseType(e: WechatMiniprogram.BaseEvent) {
    const id = +e.currentTarget.dataset.id
    this.setData({
      categoryId: id,
    })
    this.canPublish()
  },
  /**
   * 选择上传视频还是图片
   */
  chooseUpload() {
    const hasVideo = this.data.img.find((item) => item.video)
    if (!hasVideo) {
      wx.showActionSheet({
        itemList: ['图片', '视频'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              this.chooseImg()
              break
            case 1:
              this.chooseVideo()
              break
          }
        },
      })
    } else {
      this.chooseImg()
    }
  },
  /** 视频预览全屏事件捕获 */
  fullscreenchange({ detail: { fullScreen } }: { detail: any; fullScreen: boolean }) {
    this.setData({
      videoFullScreen: fullScreen,
    })
  },
  /** 选择视频 */
  chooseVideo() {
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      compressed: true,
      maxDuration: 30,
      camera: 'back',
      // success: (res) => {
      //   console.log(res)
      // },
      success: ({ tempFilePath, size }: { size: number; tempFilePath: string }) => {
        if (size > 25000000) {
          wx.showToast({
            title: '选择的视频文件过大',
            icon: 'none',
          })
          this.canPublish()
          return
        }
        this.setData({
          videoContext: wx.createVideoContext('chosen-video', this),
          videoPath: tempFilePath,
          videoSize: size,
          img: [...[{ image: '', video: tempFilePath }], ...this.data.img],
        })
        this.canPublish()
      },
      fail: () => {
        this.canPublish()
      },
    })
  },
  /** 选择图片 */
  chooseImg() {
    wx.chooseImage({
      count: 1,
      success: (res) => {
        const img =
          [...this.data.img, ...[{ image: res.tempFilePaths[0], video: '' }]].length > 4
            ? [...this.data.img, ...[{ image: res.tempFilePaths[0], video: '' }]].slice(0, 4)
            : [...this.data.img, ...[{ image: res.tempFilePaths[0], video: '' }]]
        this.setData({
          img,
        })
        this.canPublish()
      },
      fail: () => {
        this.canPublish()
      },
    })
  },
  /** 取消选择图片 */
  deletImg(e: WechatMiniprogram.BaseEvent) {
    const index = e.currentTarget.dataset.index
    const img = this.data.img
    img.splice(index, 1)
    this.setData({
      img,
    })
    this.canPublish()
  },
  /** 选择封面 */
  chooseCover(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { index },
      },
    } = e
    wx.chooseImage({
      count: 1,
      success: (res) => {
        const img = this.data.img
        img[index].image = res.tempFilePaths[0]
        this.setData({
          img,
        })
      },
    })
  },
  /** 输入标题 */
  nameInput(e: WechatMiniprogram.CustomEvent) {
    const title = e.detail.value
    this.setData({
      title,
    })
    this.canPublish()
  },
  /** 输入弹窗 */
  dscInput(e: WechatMiniprogram.CustomEvent) {
    const dsc = e.detail.value
    this.setData({
      dsc,
    })
    this.canPublish()
  },
  /** 输入价格 */
  priceInput(e: WechatMiniprogram.CustomEvent) {
    let {
      data: { sroce, price },
    } = this
    const {
      data: { mall, rechargeRatio },
    } = this
    const {
      detail: { value },
    } = e
    if (mall.pricing_policy === 'both' && sroce > 0) {
      sroce =
        sroce < value * 100 * rechargeRatio * mall.score_min_percent
          ? value * 100 * rechargeRatio * mall.score_min_percent
          : sroce
      price = value
    } else if (mall.pricing_policy === 'both' && sroce === 0) {
      sroce = value * 100 * rechargeRatio * mall.score_min_percent
      price = value
    } else {
      price = value
    }
    const marketPrice = ((price * 100 + sroce / rechargeRatio) / 100).toFixed(2)
    this.setData({
      price,
      marketPrice,
      sroce,
      iptPrice: `${price}`,
      iptSroce: `${sroce}`,
    })
    this.canPublish()
  },
  /** 输入积分 */
  sroceInput(e: WechatMiniprogram.CustomEvent) {
    let {
      data: { price, sroce },
    } = this
    const {
      data: { mall, rechargeRatio },
    } = this
    const {
      detail: { value },
    } = e
    if (mall.pricing_policy === 'both' && price > 0) {
      sroce =
        value < price * 100 * rechargeRatio * mall.score_min_percent
          ? price * 100 * rechargeRatio * mall.score_min_percent
          : value
    } else if (mall.pricing_policy === 'both' && price === 0) {
      sroce = value
      price = (sroce * mall.score_min_percent) / rechargeRatio / 100
    } else {
      sroce = value
    }
    mall.pricing_policy === 'both' ? mall.score_min_percent : e.detail.value
    const marketPrice = ((price * 100 + sroce / rechargeRatio) / 100).toFixed(2)
    this.setData({
      sroce,
      marketPrice,
      price,
      iptPrice: `${price}`,
      iptSroce: `${sroce}`,
    })
    this.canPublish()
  },
  /** 发货规则 */
  toBuyRules() {
    wx.navigateTo({
      url: '/mall/publish/buyRules/buyRules',
    })
  },
  /** 地区显示 */
  toCityRules() {
    wx.navigateTo({
      url: '/mall/publish/cityRules/cityRules',
    })
  },
  /** 隐藏添加分类输入框 */
  close() {
    this.setData({
      addTyleshow: false,
      name: '',
      count: '',
      sukIndex: '',
      inventory: '',
    })
  },
  /** 显示添加分类输入框 */
  addType() {
    this.setData({
      addTyleshow: true,
    })
  },
  /** 输入商品规格 */
  inputSuk(e: WechatMiniprogram.Input) {
    const {
      detail: { value },
    } = e
    this.setData({
      name: value,
    })
  },
  /** 输入规格差价 */
  inputSukPrice(e: WechatMiniprogram.Input) {
    const {
      detail: { value },
    } = e
    this.setData({
      count: value,
    })
  },
  /** 库存 */
  inputCount(e: WechatMiniprogram.Input) {
    const {
      detail: { value },
    } = e
    this.setData({
      inventory: value,
    })
  },
  /** 添加分类 */
  saveSuk() {
    const {
      data: { sku, name, count, sukIndex, inventory },
    } = this
    if (!name || inventory == '') return
    if (sku && sku.length > 0) {
      sku.forEach((i: any) => {
        if (i.name == name) {
          wx.showToast({
            icon: 'none',
            title: '该规格已存在',
          })
          return
        }
      })
    }
    if (sukIndex !== '') {
      this.setData({
        [`sku[${sukIndex}]`]: { name: name, extra: count, inventory: inventory },
      })
    } else {
      //TS转JS的数组需要初始化
      const skuarr = sku ? [...sku] : []
      skuarr.push({ name: name, extra: +count, inventory: +inventory })
      this.setData({
        sku: skuarr,
      })
    }
    this.close()
  },
  /** 编辑Suk */
  editSuk(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: {
          index,
          item: { name, extra, inventory },
        },
      },
    } = e
    this.setData({
      sukIndex: index,
      name,
      count: extra,
      inventory,
      addTyleshow: true,
    })
  },
  /** 删除分类 */
  deletType() {
    const {
      data: { sukIndex, sku },
    } = this
    sku.splice(+sukIndex, 1)
    this.setData({
      sku,
    })
    this.close()
  },
  /** 判断是否激活按钮 */
  canPublish() {
    const {
      data: { title, price, sroce, categoryId, img, vipProduct, vipMarketPrice },
    } = this
    let canPublish = false
    if (vipProduct == 1) {
      canPublish =
        (title != '' &&
          (+price === 0 || price > 0) &&
          (+sroce === 0 || sroce > 0) &&
          categoryId != 0 &&
          img.length > 0) ||
        this.data.edit
    } else if (vipProduct == 0) {
      canPublish =
        this.data.edit ||
        (title != '' &&
          categoryId != 0 &&
          img.length > 0 &&
          // vip.config.length == Object.keys(this.data.extra).length &&
          (+vipMarketPrice === 0 || vipMarketPrice > 0))
    }
    this.setData({
      canPublish,
    })
  },
  /** 选择会员/兑换商品 */
  chooseTypes(e: WechatMiniprogram.BaseEvent) {
    const {
      currentTarget: {
        dataset: { index },
      },
    } = e
    const {
      data: { vipProduct, currencyName, edit },
    } = this
    if (edit) return
    if (+index === +vipProduct) return
    this.setData({
      sku: [],
      vipProduct: index,
      extraPlaceholder: index == 0 ? '设置补价（元）' : `设置补${currencyName}`,
    })
  },
  async submit() {
    const {
      data: { vipProduct, extra },
    } = this
    if (+vipProduct === 0) {
      let verifyPrice = false
      Object.values(extra).some((i: any) => {
        verifyPrice = +i > +this.data.vipMarketPrice
      })
      if (verifyPrice) {
        wx.showToast({
          title: '会员价格不能高于市场价！',
          icon: 'none',
        })
        return
      }
    }
    if (!this.data.canPublish) {
      wx.showToast({ title: '请完善所有信息', icon: 'none', duration: 1000 })
      return
    }
    const img = this.data.img
    const noCover = img.find((item) => {
      return item.video && !item.image
    })
    if (noCover) {
      wx.showToast({ title: '请选择视频封面', icon: 'none', duration: 1000 })
      return
    }
    wx.navigateTo({
      url: '/mall/publish/submit/submit',
    })
  },
  /** 设置运费 */
  beFree() {
    this.setData({
      has_freight: false,
      freight: '',
    })
  },
  inputfreight(e: WechatMiniprogram.Input) {
    let {
      detail: { value },
    } = e
    const arr = value.split('.')
    if (arr.length == 1) {
      value = value.slice(0, 5)
    }
    if (+value > 0) {
      this.setData({
        has_freight: true,
        freight: value,
      })
    }
  },
  cancel() {
    wx.navigateBack({ delta: 1 })
  },
  besure() {
    wx.navigateTo({
      url: '/mine/setting/setting',
    })
  },
})
